/**
 * @author klv
 */
 /*
(function(window){
    var elements=[];
    var currentIndex=0;
    var toNext=function(){
        currentIndex++;
		var length=elements.length;
		if(length==0) return;
        if(currentIndex>=length){
            currentIndex=0;
        }
        elements[currentIndex].focus();
    };
    var click=function(e){
		if(elements.length==0) return;
        elements[currentIndex].click();
    };
	var focusCurrent=function(){
		if(elements.length==0) return;
		elements[currentIndex].focus();
	};
    var register=function(element){
        elements.push(element);
		if(elements.length==1){
			focusCurrent();
		};
    };
    var unregister=function(element){
        for(var i=0,l=elements.length;i<l;i++){
            if(elements[i]==element){
                elements.splice(i,1);
                break;
            }
        }
    };
    $(document).bind("keyup.tabswidth", function(e){
        if(e.keyCode == 9){//tab
            toNext();
        }else if(e.keyCode == 13){//enter
            click();
        }
    });
    return window.tabSwitch={
        register:register,
        unregister:unregister
    }
})(window);
*/
function MessageSender(){
    this.type = '';//workspace,widget,message
    this.isOpen = false;
	this.receive=[];
	this.subject="";
	this.message="";
	this.config={
		subjectMax:1000
	};
	this.wsID="";
	this.widgetID="";
    this._init();
}

MessageSender.prototype = {
	_init: function(){
		var headHTML =	'<div class="sendmessage-mailaddress">'+
							'<div class="mailaddress-title">'+
								'<span class="title">Email address (es)</span>'+
							'</div>'+
							'<div class="mailaddress-inputbox">'+
								'<textarea class="qs-ui-txt textarea" id="textareaReceiver"></textarea>'+
							'</div>'+
						'</div>';
		var attachHTML ='<div class="sendmessage-attach">'+
							'<div class="attach-title">'+
								'<span class="title">Attach</span>'+
							'</div>'+
							'<div class="attach-inputbox"></div>'+
						'</div>';
		var bodyHTML =	'<div class="sendmessage-subject">'+
							'<div class="subject-title">'+
								'<span class="title">Subject</span>'+
							'</div>'+
							'<div class="subject-inputbox">'+
								//'<textarea  class="qs-ui-txt textarea"></textarea>'+
								'<input type="text" class="qs-ui-ipt" value="" />'+
							'</div>'+
						'</div>'+
						'<div class="sendmessage-message">'+
							'<div class="message-title">'+
								'<span class="title">Message (optional)</span>'+
							'</div>'+
							'<div class="message-inputbox">'+
								'<textarea class="qs-ui-txt qs-share-message"></textarea>'+
							'</div>'+
						'</div>'+attachHTML;
		this.html = '<div class="rtq-share-sendmessage">'+
						'<div class="bottom-line hd">'+
							headHTML+
						'</div>'+
						'<div class="bottom-line bd">'+
							bodyHTML+
						'</div>'+
						'<div class="ft">'+
							'<div class="operate">'+
								'<a class="qs-ui-btn send" href="#">Send</a>'+
								'<a class="qs-ui-btn cancel" href="#">Cancel</a>'+
							'</div>'+
						'</div>'+
					'</div>';
		this._createWin();
		this._getContact();
//		this._registerTabSwitch();
		this._setTabIndex();
	},
	open: function(type,wsid,widgetid,message){
		this.type = typeof type == 'undefined' ? "message" : type;//0:workspace;1:widget
		this.wsID = typeof wsid == 'undefined' ? WorkspaceTabs.currentTab.id : wsid;
		this.widgetID = typeof widgetid == 'undefined' ? null : widgetid;
		if (type == "message") {
			this.win.setTitle("Send Message");
			this.attachDOM.hide();
			this._initMessageSend(message);
		}else{
			if (wsid<= -10000 && type!="widget") {
				Util.confirm("Default workspace selected, save as new workspace?",function(b){
					if(b){
						workspaceManager.saveAsHandler();
					}
				});
                return {status:false};
            }else{
				if(type=="widget"){
					this.win.setTitle("Sharing "+message);
				}else{
					this.win.setTitle("Sharing workspace");
				}
			}
			this.attachDOM.hide();
		}
		this.win.setIndex();
		this.win.show();
		this.isOpen = true;
		this.win.contentMask.hide();
	},
	_initMessageSend:function(message){
		if(message){
			this.receiveinputDOM.val(message.senderAddress+',');
            this.subjectinputDOM.val(String.format("RE:{0}",message.subject));
            this.messageinputDOM.val(this._structBody(message));
		}
	},
	_structBody:function(message){
		return String.format("\r\n\r\n\r\n-------\r\nFrom:{0}\r\nSent:{1}\r\nTo:{2}\r\nSubject:{3}\r\n{4}",
		  message.senderAddress,
		  message.createTime,
		  message.receiverAddress,
		  message.subject,
		  message.content
		);
	},
	_getContact:function(){
		DBHelper.getContact(null,function(o){
			var o=o.replace(/\r\n/g, "");
            if ($.trim(o) != '') {
				o=o.substring(1,o.length-1).split(',')
				for(var i=0,l=o.length;i<l;i++){
					QS_contactlist.push(o[i].substring(1,o[i].length-1));
				}
            }
		});
	},
	_setTabIndex:function(){
/*		tabSwitch.register(this.receiveinputDOM);
		tabSwitch.register(this.subjectinputDOM);
		tabSwitch.register(this.messageinputDOM);
		//tabSwitch.register(this.attachDOM);
		tabSwitch.register(this.pn.find(".operate .send"));
		tabSwitch.register(this.pn.find(".operate .cancel"));
		*/
		var tabindex = 1;
		this.receiveinputDOM.attr("tabindex", tabindex++);
		this.subjectinputDOM.attr("tabindex", tabindex++);
		this.messageinputDOM.attr("tabindex", tabindex++);
		this.pn.find(".operate .send").attr("tabindex", tabindex++);
		this.pn.find(".operate .cancel").attr("tabindex", tabindex++);
	},
	_createWin: function(){
		var self = this;
		this.win = new Util.RtqWindow(document.body, {
			windowReady: function(obj){
				obj.setHtml(self.html);
				self.pn = obj.el;
				self.receiveinputDOM = self.pn.find(".sendmessage-mailaddress").find("textarea");
				self.subjectinputDOM = self.pn.find(".sendmessage-subject").find(".qs-ui-ipt");
				self.messageinputDOM = self.pn.find(".sendmessage-message").find("textarea");
				self.attachDOM = self.pn.find(".sendmessage-attach");
				self.attachDOM.hide();
				self._registerACB();
				self.pn.find(".operate").bind("click", function(e){
					var target = $(e.target);
					if (target.hasClass('cancel')) {
						self.hide();
					}
					else 
						if (target.hasClass('send')) {
							/* prompt user to save the workspace if send a share message.
							if(Terminal.getConfig('TurnOffAutoSave')){
								Util.confirm(QS_Lang.text["sharesaveconfirm"], function(b){
									if(b){
										self._send();
									}
								});
							}else{
								workspaceManager.autoSave();
							}
							*/
							self._send();
						}
				});
			},
			beforeClosed: function(){
				self._reset();
				self.isOpen = false;
			},
			onResized: function(win, width, height){
                self.changeOutSize(width, height - 26);                    
            }
		}, {
			title: 'Sharing',
			top: 100,
			width: 500,
			height: 500,
			minHeight: 410,
			resizable: true,
			isGlobal: true,
			hasSettingPanel: false,
			closeAction: 'hide'
		});
		rtqWindowGroup.register(this.win);
		this.win.hide();
		this.changeOutSize(500,500-26);
	},
	hide: function(){
		if (this.isOpen) {
			this.win.hide();
			this._reset();
			this.isOpen = false;
		}
	},
	_reset: function(){
		this.receiveinputDOM.val('');
		this.subjectinputDOM.val('');
		this.messageinputDOM.val('');
		this.attachDOM.val('');
		this.type = '';
	},
	clear: function(){
		for (var p in this) {
			if (!p || p == 'clear') {
				continue;
			}
			this[p] = null;
			delete this[p];
		}
	},
	_registerACB: function(){
		new simpleAutoCompleteBox("textareaReceiver", {
			onclick: function(index){
				return QS_contactlist[index];
			}
		}, null).init();
	},
	changeOutSize:function(w,h){
		var parent = this.pn;
        w = w || parent.width();
        h = h || parent.height();
		var otherheight=this.attachDOM.css("display")=="none"?239:239+42;
        this.messageinputDOM.css({width:w-15,height:h-otherheight});
	},
	_send: function(){
		var receive = this.receiveinputDOM.val();
		this.receive=[];
		var subject = this.subjectinputDOM.val();
		var message = this.messageinputDOM.val();
		var array = receive.split(",");
		var existReciver={};
		if (receive.length == 0) {
			Util.message("At least one recipient should be chosen.");
			return ;
		}
		for (var i = 0; i < array.length; i++) {
			if (array[i].length == 0) 
				continue;
			array[i]=$.trim(array[i]);
			if(existReciver[array[i]]){// remove the same Reciver email address
				continue;
			}
			existReciver[array[i]]=true;
			if (!QS_Validator.validate(array[i], "email")) {
				Util.message(String.format("This email's({0}) format is wrong", array[i]));
				this.receive = [];
				return ;
			}
			else {
				if($.inArray(array[i],QS_contactlist)==-1){
					QS_contactlist.push(array[i]);
				}
				this.receive.push(array[i]);
			}
		}
		this.subject = subject;
		this.message = message;
		var self = this;
		if (subject.length == 0) {
			Util.confirm(QS_Lang.text["nullsubject"], function(b){
				if (b) {
					self._sendWithoutValidation();
				}
			});
		}else if(subject.length > this.config.subjectMax){
			Util.message(String.format("Characters limit for Subject is {0}.", this.config.subjectMax));
			return;
		}else{
			
			this._sendWithoutValidation();
		}
	},
	_sendWithoutValidation:function(){
		this.win.contentMask.show();
		var self=this;
		if (this.type != 'message') {
			var shareid = null;
			if (QS_ShareModule == null) QS_ShareModule = new ShareModule();
			QS_ShareModule.send(this.widgetID==null?"0":"1", this.wsID, this.widgetID, this.receive, this.subject, this.message,function(result){
				self.win.contentMask.hide();				
				if (result.sharingId) {
					self.hide();
				};
			});
		}else{
			DBHelper.sendMessage({
				senderAddress:QS_UserNAME,
				receiverAddress:this.receive.join(','),
				messageType:0,//0:message, 1:share, 2:alert, 3:system; 
				subject:this.subject,
				content:this.message,
				attachment:""
			},function(o){
				var o=o.replace(/\r\n/g, "");
                if ($.trim(o) != '') {
                    o = $.evalJSON(o);
                }
                else{
                    o={};
                }
				self.win.contentMask.hide();									
				if(o.error&&o.error.length>0){
					var errorDetail={};
                    for(var i=0,l=o.error.length;i<l;i++){
                        //o.error[i].email,o.error[i].code
						var code=o.error[i].code;
						var mail=o.error[i].email;
						var index=$.inArray(mail,QS_contactlist);
						if(index!=-1){
		                    QS_contactlist.splice(index,1);
		                }
						
						if(typeof errorDetail[code]=="undefined"){
							errorDetail[code]=[];
						}
						errorDetail[code].push(mail);
                    }
                    var errorstr="";
					for(var code in errorDetail){
						if(code.indexOf('quota limits') != -1){
							errorstr = 'Your mailbox has exceeded one or more size limits set by your administrator. <br />Your mailbox size is 200 messages.';
						}else{
							var length=errorDetail[code].length;
							errorstr=String.format("The following recipient{0} {1} {2}:<br />{3};<br />",length>1?"s":"",length>1?"are":"is",code,errorDetail[code].join(','))
						}
					}
                    Util.message(errorstr);
					if(o.error.length!=self.receive.length){
						self.hide();
					}
				}else{
					self.hide();
				}
			});
		}
	}
	
}
var QS_MessageSender = null;
var QS_contactlist=[];
var simpleAutoCompleteBox = function(id, callback, cfg){
    this.id = id;
    this.input = $("#" + this.id);
    this.data = [];
    this.matchData = null;
    this.boxIsAvailable = false;
    this.dom = {};
	this.isSuffix=false;
    this.callback = callback;
    this.cfg = $.extend({
        width:"auto",
        separator: ',',
		defaultsuffx:["morningstar.com"],
		numbers:10
    }, true, cfg)
    this.textChangeTimeout = null;
    this.HTML = "<div class='simpleAutoCompleteBox'><div class='simpleAutoCompleteBoxWrap'><ul></ul></div></div>";
    
};
simpleAutoCompleteBox.prototype = {
    init: function(){
        this._generateDom();
        var sf = this;
		this.input.bind("keydown.simpleAutoCompleteBox", function(e){
			if (sf.visible&&(e.keyCode == 13 || e.keyCode == 40 || e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39)) {
				e.preventDefault();
			}
		});
        this.input.bind("keyup.simpleAutoCompleteBox", function(e){
			if(e.keyCode == 13){//enter
				if(sf.visible&&sf.dom.ul.currentindex>-1){
					sf.dom.ul.find("li").eq(sf.dom.ul.currentindex).click();
				}
				return;
			}
            if (e.keyCode == 40 || e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 ) {//down,left,up,right
                if(sf.visible){
					switch(e.keyCode){
						case 40://down
							sf.dom.ul.currentindex=(sf.dom.ul.currentindex+1)%(sf.dom.ul.find("li").length);
							break;
						case 38://up
							sf.dom.ul.currentindex=sf.dom.ul.currentindex<=0?sf.dom.ul.find("li").length-1:sf.dom.ul.currentindex-1;
							break;
						case 39://rigth
						case 37://left
						    break;
					}
					sf.setLiHover();
					return;
				}
            }
			if(e.keyCode == 50){//@
				sf.isSuffix=true;
			}
            if (sf.textChangeTimeout != null) {
                clearTimeout(sf.textChangeTimeout);
            }
            sf.textChangeTimeout = setTimeout(function(){
                if (!sf.boxIsAvailable) {
                    sf.dom.el.css({
                        top: sf.input.offset().top + sf.input.outerHeight() + "px",
                        left: sf.input.offset().left
                    });
                }
				var val = sf.input.val();
                if (val == "") {
                    sf.hide();
                    return;
                }
                var array = val.split(sf.cfg.separator);
				if ($.trim(array[array.length - 1]).length > 0) {
					sf.matchData = sf._matchString(array[array.length - 1].replace(/\r/g,'').replace(/\n/g,''));
					sf._bindUI();
					sf.textChangeTimeout = null;
				}
            }, 100)
        });
        this.dom.el.bind("click.simpleAutoCompleteBox", function(e){
            var o = $(e.target).closest("li");
            var key = o.attr("index");
			var cate= o.attr("cate");
            if (sf.callback != null && typeof(sf.callback.onclick) == "function") {
                var value = sf.isSuffix?sf.cfg.defaultsuffx[key]:sf.callback.onclick(key);
                var prevalue = sf.input.val().replace(/\r/g,'').replace(/\n/g,'');
				if (!sf.isSuffix) {
					var array = prevalue.split(sf.cfg.separator);
					array[array.length - 1] = value;
					sf.input.val(array.join(sf.cfg.separator) + sf.cfg.separator);
				}
				else{
					sf.input.val(prevalue+value+sf.cfg.separator);
					sf.isSuffix=false;
				}
            }
            sf.hide();
        });
        this.dom.ul.bind("mouseover.simpleAutoCompleteBox", function(e){
            var o = $(e.target).closest("li");
            o.parent().find("li").removeClass("mover");
            o.addClass("mover");
			sf.dom.ul.currentindex=parseInt(o.attr("index"));
        });
        $(document.body).bind("click.simpleAutoCompleteBox", function(){
            sf.hide();
        })
    },
	setLiHover:function(){
		if(this.dom.ul.currentindex>-1&&this.dom.ul.find("li").length>this.dom.ul.currentindex){
		 	 var li=this.dom.ul.find("li").eq(this.dom.ul.currentindex);
         	 li.parent().find("li").removeClass("mover");
             li.addClass("mover");
		}
	},
    setData: function(data){
        this.data = data;
    },
    show: function(){
        this.dom.el.show();
		this.visible=true;
    },
    hide: function(){
        this.dom.el.hide();
		this.visible=false;
    },
    _matchString: function(kw){
        var rgx = new RegExp("^" + kw, "i");
        var tmatch = null;
        var rtn = {};
        for (var i = 0; i < QS_contactlist.length; i++) {
            tmatch = QS_contactlist[i].match(rgx);
            if (tmatch != null) {
                rtn[i] = QS_contactlist[i].replace(rgx, "<span class='highlight'>" + tmatch[0] + "</span>");
            }
        }
		if (this.isSuffix) {
			rtn["suffix"] = [];
			for (i = 0; i < this.cfg.defaultsuffx.length; i++) {
				rtn["suffix"].push(String.format("<span class='highlight'>{0}</span>", this.cfg.defaultsuffx[i]));
			}
		}
        return rtn;
    },
    _bindUI: function(){
        var str = "";
		var count=0;
		if (this.isSuffix && typeof this.matchData["suffix"] != 'undefined') {
			for (i = 0; i < this.matchData["suffix"].length; i++) {
				str += '<li cate="suffix" index=' + i + '>' + this.matchData["suffix"][i] + '</li>';
			}
			delete this.matchData["suffix"];
		}
        for (var i in this.matchData) {
            if (typeof(this.matchData[i]) != "undefined") {
                str += '<li index=' + i + '>' + this.matchData[i] + '</li>';
            }
			count++;
			if(count==this.cfg.numbers) break;
        }
        this.dom.ul.html("");
		if (str.length != 0) {
			this.dom.ul.append(str);
			this.dom.ul.currentindex=-1;
			this.show();
		}
    },
    _generateDom: function(){
        this.dom.el = $(this.HTML).appendTo(document.body);
        this.dom.el.css({
            width: this.cfg.width
        });
        this.dom.wrap = this.dom.el.find(".simpleAutoCompleteBoxWrap");
        this.dom.ul = this.dom.wrap.find("ul");
        this.hide();
    }
};


